package com.woniuxy.cloud.carl.order.app.apiImpl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.cloud.Aspect.log.Log;
import com.woniuxy.cloud.carl.carlstation.client.StaffClient;
import com.woniuxy.cloud.carl.carlstation.client.dto.StaffDto;
import com.woniuxy.cloud.carl.order.client.ExpressManageClient;
import com.woniuxy.cloud.carl.order.client.OrderManageClient;
import com.woniuxy.cloud.carl.order.client.param.*;
import com.woniuxy.cloud.carl.order.common.TransStatusEnum;
import com.woniuxy.cloud.carl.order.infra.model.*;
import com.woniuxy.cloud.carl.order.service.*;
import com.woniuxy.exceptions.MallException;
import com.woniuxy.result.CommonResultCodeEnum;
import com.woniuxy.result.Result;
import com.woniuxy.utils.Assert;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.Date;

@RestController
public class ExpressManageApiImpl implements ExpressManageClient {
    @Autowired
    ServiceLogService serviceLogService;
    @Autowired
    TransItemService transItemService;
    @Autowired
    UserDeliveryService userDeliveryService;
    @Autowired
    SkuOrderItemService skuOrderItemService;
    @Autowired
    OrderItemService orderItemService;
    @Autowired
    OrderService orderService;
    @Override
    public Result addExpressForUser(AddExpressForUserParam param) {
        SkuOrderItem item = skuOrderItemService.getById(param.getSkuorderItemId());
        OrderItem byId = orderItemService.getById(item.getOrderItemId());
        Order order = orderService.getById(byId.getOrderId());
        UserDelivery delivery = BeanUtil.copyProperties(param, UserDelivery.class);
        delivery.setCreateDate(new Date());
        delivery.setDeliveryStatus(0);
        delivery.setOrderNum(order.getOrderNum());
        delivery.setUserId(order.getUserId());
        delivery.setOrderItemId(item.getOrderItemId());
        userDeliveryService.save(delivery);
        return Result.success();
    }

    @Override
    @Log("新增商家物流")
    public Result addExpressForStore(AddExpressForStoreParam param) {
        TransItem transItem = BeanUtil.copyProperties(param, TransItem.class);
        transItem.setCreateDate(new Date());
        transItem.setTransStatus(TransStatusEnum.APPLY.getCode());
        transItemService.save(transItem);
        return Result.success();
    }

    @Override
    @Log("修改用户物流状态")
    public Result setExpressState(UpdateExpressParam param) {
        UserDelivery userDelivery = BeanUtil.copyProperties(param, UserDelivery.class);
        boolean b = userDeliveryService.updateById(userDelivery);
        if (b) return Result.success();
        return Result.fail("更新失败");
    }

    @Override
    @Log("修改商家物流状态")
    public Result setTransState(UpdateTransParam param) {
        Assert.state(param.getTransItemId()!=null,"物流信息不能为空");
        TransItem transItem = BeanUtil.copyProperties(param, TransItem.class);
        TransStatusEnum anEnum = TransStatusEnum.getEnum(param.getTransStatus());
        Assert.state(anEnum!=null,"状态信息错误");
        switch (anEnum){
            case REJECT:{
                Assert.state(transItem.getRejectReason()!=null,"驳回理由不能为空");
                break;
            }
            case SENDING:{
                Assert.state(transItem.getDeliveryNo()!=null,"运单号不能为空");
            }
            default:{
                break;
            }
        }
        transItemService.updateById(transItem);
        return Result.success();
    }
    @Autowired
    ServiceService serviceService;
    @Autowired
    StaffClient staffClient;
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    ServiceOrderItemService serviceOrderItemService;
    @Autowired
    OrderManageApiImpl orderManageApi;
    @Override
    @Log("添加服务日志")
    public Result addServiceLog(AddServiceLogParam param) {

//        RMap<Long, Object> map1 = redissonClient.getMap("cost:code" + 1);//1是userId
//        map1.put(orderItemId,Object);//对象里面放二维码连接、核销码


        RMap<String, Long> map = redissonClient.getMap("service:code" + param.getCostCode());
        if (map.isEmpty())throw new MallException(CommonResultCodeEnum.DATA_NOT_FOUND,"核销码错误或已过期");
        Long orderItemId = map.get("order:item");
        Long userId = map.get("user:id");
        //判断消费门店是否正确
        ServiceOrderItem serviceOrderItem = serviceOrderItemService.getOne(new QueryWrapper<ServiceOrderItem>()
                .eq("order_item_id", orderItemId));
        if (param.getStoreId()!=serviceOrderItem.getStoreId())
            throw new MallException(CommonResultCodeEnum.ILLEGAL_STATE,"核销码与门店不匹配");
        //判断员工是否存在并属于这个店
        Result<StaffDto> staffById = staffClient.findStaffById(param.getStaffId());
        StaffDto staff = staffById.getData();
        if (staff.getStoreId()!= param.getStoreId())
            throw new MallException(CommonResultCodeEnum.ILLEGAL_STATE,"员工与门店不匹配");
        ServiceLog serviceLog = BeanUtil.copyProperties(param, ServiceLog.class);
        serviceLog.setServiceState(1);//服务中
        serviceLog.setUserId(userId.intValue());
        serviceLog.setOrderItemId(orderItemId);
        serviceLog.setServiceStartTime(new Date());
        serviceLogService.save(serviceLog);
        map.delete();
        orderManageApi.useCode(orderItemId);
        return Result.success();
    }

    @Override
    @Log("修改服务日志状态")
    public Result setServiceLog(SetServiceLogParam param) {
        ServiceLog serviceLog = BeanUtil.copyProperties(param, ServiceLog.class);
        serviceLog.setServiceEndTime(new Date());
        boolean b = serviceLogService.updateById(serviceLog);
        if (b) return Result.success(CommonResultCodeEnum.SUCCESS,"修改成功",null);
        return Result.fail("修改失败");
    }
    @Autowired
    FirstTypeService firstTypeService;
    @Autowired
    SecondTypeService secondTypeService;
    @Autowired
    ThirdTypeService thirdTypeService;
//    @Override
//    @Log("添加服务类别")
//    public Result addServiceType(AddServiceTypeParam param) {
//        if (param.getTypeFlag()==1){
//            FirstType type_name = firstTypeService.getOne(new QueryWrapper<FirstType>()
//                    .eq("type_name", param.getTypeName()));
//            Assert.state(type_name==null,"请勿重复添加");
//            FirstType firstType = new FirstType();
//            firstType.setTypeName(param.getTypeName());
//            firstTypeService.save(firstType);
//        }
//        if (param.getTypeFlag()==2){
//            SecondType type_name = secondTypeService.getOne(new QueryWrapper<SecondType>()
//                    .eq("second_type_name", param.getTypeName()));
//            Assert.state(type_name==null,"请勿重复添加");
//            SecondType secondType = new SecondType();
//            secondType.setSecondTypeName(param.getTypeName());
//            secondType.setFirstTypeId(param.getParentTypeId());
//            secondTypeService.save(secondType);
//        }
//        if (param.getTypeFlag()==3){
//            ThirdType type_name = thirdTypeService.getOne(new QueryWrapper<ThirdType>()
//                    .eq("third_type_name", param.getTypeName()));
//            Assert.state(type_name==null,"请勿重复添加");
//            ThirdType thirdType = new ThirdType();
//            thirdType.setThirdTypeName(param.getTypeName());
//            thirdType.setSecondTypeId(param.getParentTypeId());
//            thirdTypeService.save(thirdType);
//        }
//        return Result.success();
//    }
}
